package com.vf.admin.fiwork.aop;


import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.common.redis.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class EnableApiLimitAop {

    @Autowired
    private RedisUtil redisUtil;

    @Around("@annotation(limit)")
    public Object EnableApiLimit(ProceedingJoinPoint point,EnableApiLimit limit) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ClientBaseController result = new ClientBaseController();
        if(request == null) return result.errorJSON("Missing HttpServletRequest parameter in method");
        String ip = request.getRemoteHost ();
        String requestURI = request.getRequestURI();
        //请求的方法
        String method = request.getMethod();
        String key = RedisKeys.APILIMIT + ip + "_" + requestURI;
        boolean exists = redisUtil.hasKey(key);
        if(exists && redisUtil.getExpire(key)>0){
            redisUtil.incr(key, 1);
            Object sendcountObj = redisUtil.get(key);
            System.out.println("-----------------API:"+key+"--------------请求次数:"+Integer.valueOf(sendcountObj.toString()));
            if(sendcountObj!=null && Integer.valueOf(sendcountObj.toString()) > limit.count()){
                return result.errorJSON("The number of requests for interface exceeds the limit");
            }
        }else {
            //记录请求次数
            redisUtil.del(key);
            redisUtil.set(key,1, limit.time()/1000);
        }
        return point.proceed();
    }
}
